package com.ting.test.algorithms.大厂刷题班;

/**
 * 给定一个字符串数组，求所有字符串的最长公共前缀
 */

public class 求一个字符数组的最长公共前缀 {
    public static void main(String[] args) {
        String[] arr = new String[]{"dsdaf", "dsfa", "dsfsad", "dsfa"};
        String str = process(arr);
        System.out.println(str);
    }

    private static String process(String[] arr) {
        if (arr == null) {
            return null;
        }
        if (arr.length == 1) {
            return arr[0];
        }

        final char[] results = arr[0].toCharArray();
        int size = results.length;
        for (int i = 1; i < arr.length; i++) {
            final char[] indexChars = arr[i].toCharArray();
            for (int index = 0; index < size; index++) {
                if (results[index] != indexChars[index]) {
                    size = index;
                }
            }
        }
        return new String(results, 0, size);
    }
}
